package cn.apestar.modules.common.school.init;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.ClientProtocolException;

import com.alibaba.fastjson.JSON;

import cn.apestar.common.utils.JedisUtils;
import cn.apestar.common.utils.SpringContextHolder;
import cn.apestar.modules.common.school.entity.Deposit;
import cn.apestar.modules.common.school.entity.School;
import cn.apestar.modules.common.school.fetch.AdressFetch;
import cn.apestar.modules.common.school.fetch.PageFetch;
import cn.apestar.modules.common.school.fetch.SchoolFetch;
import cn.apestar.modules.common.school.service.DepositService;
import cn.apestar.modules.common.school.service.SchoolService;
import cn.apestar.modules.sms.HttpUtil;
import cn.apestar.modules.sys.entity.Area;
import cn.apestar.modules.sys.service.AreaService;

public class BaiduMap extends Thread {

    List list = new ArrayList();

    public static String cacheKey = "CACHE_FETCH";

    @Override
    public void run() {

        //
        // list = new ArrayList();
        // // initLocation();
        // for (int i = 0; i < 6; i++) {
        // initData(i);
        // }
        initSearch();
    }

    public ArrayList listKey = new ArrayList();

    public String city = "厦门";

    public String cityCd = "厦门";

    public String type;

    boolean flag = false;

    public boolean isFlag() {

        return flag;
    }

    public void setFlag(boolean flag) {

        this.flag = flag;
    }

    public String getType() {

        return type;
    }

    public void setType(String type) {

        this.type = type;
    }

    public String getCityCd() {

        return cityCd;
    }

    public void setCityCd(String cityCd) {

        this.cityCd = cityCd;
    }

    public String getCity() {

        return city;
    }

    public void setCity(String city) {

        this.city = city;
    }

    // 查询URL
    private String search_url = "http://api.map.baidu.com/place/v2/search?q={type}&region={city}&output=json&ak={key}&page_size=20&page_num={page}";

    // 查询URL
    private String arround_url = "http://api.map.baidu.com/place/v2/search?query={type}&scope=2&location={location}&radius=20000000&output=json&ak={key}&page_size=20&page_num=0";

    //
    private String location_url = "http://api.map.baidu.com/geocoder/v2/?address={city}&output=json&ak={key}&callback=showLocation";

    public void init() {

        listKey.add("BZzlDjEFFUsKbv0H7U11UcB9");
        listKey.add("D9b1b5bcad874f64776ea8656916e6c7");

        // 初始化KEY
        search_url = search_url.replace("{key}", "BZzlDjEFFUsKbv0H7U11UcB9");
        // 初始化市公司
        search_url = search_url.replace("{city}", getCity());
    }

    public void initLocation() {

        AreaService areaService = SpringContextHolder.getBean(AreaService.class);
        List<Area> areaList = areaService.getFetchList();
        // 初始化KEY
        location_url = location_url.replace("{key}", "BZzlDjEFFUsKbv0H7U11UcB9");
        for (int i = 0; i < areaList.size(); i++) {
            try {
                this.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            saveSysArea(areaList.get(i), location_url);
        }
    }

    public void initData() {

        String type = "小学";
        // 初始化查询类型
        search_url = search_url.replace("{type}", type);
        int page = -1;
        geSchoolList(search_url, page);
    }

    /**
     * 抓取POI
     * @author lvh 2016年4月3日 下午5:10:15</br>
     * @return void
     */
    public void initData(int index) {

        String[] typeArray = new String[] {"托管" , "托教" , "午托" , "晚托" , "托辅" , "小饭桌"};
        search_url = search_url.replace("{key}", "BZzlDjEFFUsKbv0H7U11UcB9");
        String type = typeArray[index].toString();

        AreaService areaService = SpringContextHolder.getBean(AreaService.class);
        Area area = new Area();
        area.setParentId("00101");
        List<Area> areaList = areaService.getFetchListHave(area);
        for (int i = 0; i < areaList.size(); i++) {
            Area areasingle = areaList.get(i);
            String location = areasingle.getX() + "," + areasingle.getY();
            // 初始化查询类型
            this.cityCd = areasingle.getCode();
            String reloadUrl = search_url.replace("{city}", areasingle.getName());
            reloadUrl = reloadUrl.replace("{type}", type);
            int page = -1;
            try {
                this.sleep(200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            getDepositList(reloadUrl, page, areasingle);
        }
    }

    /**
     * 抓取POI
     * @author lvh 2016年4月3日 下午5:10:15</br>
     * @return void
     */
    public void initSearch() {

        flag = false;
        if (JedisUtils.exists(cacheKey)) {
            String m = JedisUtils.get(cacheKey);
            if ("0".equals(m))
                flag = true;
        }

        if (flag)
            return;
        JedisUtils.set(cacheKey, "0", 0);
        search_url = search_url.replace("{key}", "BZzlDjEFFUsKbv0H7U11UcB9");
        String type = this.getType();
        Area areasingle = new Area();
        areasingle.setName(this.getCity());
        String reloadUrl = search_url.replace("{city}", this.getCity());
        reloadUrl = reloadUrl.replace("{type}", type);
        int page = -1;
        try {
            this.sleep(200);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JedisUtils.del(cacheKey);
        }
        getDepositList(reloadUrl, page, areasingle);
        JedisUtils.del(cacheKey);
    }

    public List<School> geSchoolList(String search_url, int page) {

        page = page + 1;
        int index = search_url.indexOf("page_num=");
        search_url = search_url.substring(0, index);
        search_url = search_url + "page_num=" + page;
        try {
            String json = HttpUtil.ExecutionGET(search_url, null);
            PageFetch pageList = JSON.parseObject(json, PageFetch.class);
            if (!pageList.getResults().isEmpty()) {
                saveSchool(pageList.getResults());
                geSchoolList(search_url, page);
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (Exception e) {
            // TODO Auto-generated catch block
        }
        return new ArrayList();
    }

    /**
     * 托管
     * @author lvh 2016年4月7日 下午4:49:42</br>
     * @param search_url
     * @param page
     * @return
     * @return List<School>
     */
    public List<Deposit> getDepositList(String search_url, int page, Area areasingle) {

        page = page + 1;
        int index = search_url.indexOf("page_num=");
        search_url = search_url.substring(0, index);
        search_url = search_url + "page_num=" + page;
        try {
            System.out.println(search_url);
            String json = HttpUtil.ExecutionGET(search_url, null);
            PageFetch pageList = JSON.parseObject(json, PageFetch.class);
            if (!pageList.getResults().isEmpty()) {
                saveDeposit(pageList.getResults(), areasingle);
                getDepositList(search_url, page, areasingle);
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            System.out.println(e.getMessage());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println(e.getMessage());
        }
        return new ArrayList();
    }

    public void saveSchool(List<SchoolFetch> schoolList) {

        SchoolService schoolServoce = SpringContextHolder.getBean(SchoolService.class);
        for (int i = 0; i < schoolList.size(); i++) {
            SchoolFetch schoolFetch = schoolList.get(i);
            School school = new School();
            school.setAddress(schoolFetch.getAddress());
            school.setSchoolName(schoolFetch.getName());
            school.setPhone(schoolFetch.getTelephone());
            school.setLogo(schoolFetch.getStreet_id());
            school.setRemarks(schoolFetch.getDetail());
            school.setLat(schoolFetch.getLocation().getLat());
            school.setLng(schoolFetch.getLocation().getLng());
            schoolServoce.save(school);
        }

    }

    public void saveDeposit(List<SchoolFetch> schoolList, Area areasingle) {

        DepositService schoolServoce = SpringContextHolder.getBean(DepositService.class);
        for (int i = 0; i < schoolList.size(); i++) {
            SchoolFetch schoolFetch = schoolList.get(i);
            if (list.contains(schoolFetch.getName())) {
                continue;
            }
            Deposit school = new Deposit();
            school.setAddress(schoolFetch.getAddress());
            school.setCity(areasingle.getName());
            school.setSchoolName(schoolFetch.getName());
            school.setPhone(schoolFetch.getTelephone());
            school.setLogo(schoolFetch.getStreet_id());
            school.setRemarks(schoolFetch.getDetail());
            school.setLat(schoolFetch.getLocation().getLat());
            school.setLng(schoolFetch.getLocation().getLng());
            schoolServoce.save(school);
            list.add(schoolFetch.getName());
        }

    }

    /**
     * 更新坐标
     * @author lvh 2016年4月3日 下午5:55:13</br>
     * @param area
     * @return void
     */
    public void saveSysArea(Area area, String search_url) {

        // 初始化市公司
        search_url = search_url.replace("{city}", area.getName());

        AreaService areaService = SpringContextHolder.getBean(AreaService.class);
        search_url = search_url.replace("{city}", area.getName());
        System.out.println(search_url);
        try {
            String json = HttpUtil.ExecutionGET(search_url, null);
            json = json.replace("showLocation&&showLocation(", "");
            json = json.replace(")", "");
            AdressFetch address = JSON.parseObject(json, AdressFetch.class);
            area.setX(address.getResult().getLocation().getLat());
            area.setY(address.getResult().getLocation().getLng());
            areaService.updateLatLng(area);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (Exception e) {
            // TODO Auto-generated catch block
        }
    }
}
